package com.xt.service.impl;

import com.xt.bean.Module;
import com.xt.bean.Role;
import com.xt.bean.User;
import com.xt.dao.RoleRepository;
import com.xt.service.ModuleService;
import com.xt.service.RoleService;
import com.xt.service.UserService;
import com.xt.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by XT on 2018/5/3.
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleRepository rr;
    @Autowired
    private UserService us;
    @Autowired
    private ModuleService ms;

    @Override
    public void deleteRole(String roleid) {
        //删除关联关系里面的数据
        Role role = rr.findOne(roleid);
        String[] userIds = role.getUserIds();
        String[] moduleIds = role.getModuleIds();

        //删除user里面的角色信息
        for (String userid : userIds){
            User user = us.getUserById(userid);
            List<String> newRoleIdList = Arrays.asList(user.getRolesId());
            newRoleIdList.remove(roleid);
            String[] newRoleIds = (String[]) newRoleIdList.toArray();
            user.setRolesId(newRoleIds);
            us.saveOrUpdateUser(user);
        }

        //删除module里面的关联数据
        for (String moduleid : moduleIds){
            Module module = ms.getModuleById(moduleid);
            String[] roleIds = module.getRoleIds();
            List<String> roleList = Arrays.asList(roleIds);
            roleList.remove(roleid);
            String[] newRoleIds = (String[]) roleList.toArray();
            module.setRoleIds(newRoleIds);
            ms.saveOrUpdateModule(module);
        }

        rr.delete(roleid);
    }

    @Override
    public void saveOrUpdateRole(Role role) {
        if (StringUtils.isEmpty(role.getId())) {
            //新增操作，设置密码加密和创建时间
            role.setCreateDate(new Date());
            //设置创建的用户ID
//            role.setAuthorUserId();
        }
        role.setUpdateDate(new Date());
        rr.save(role);
    }

    @Override
    public Role getRoleById(String id) {
        return rr.findOne(id);
    }

    @Override
    public Page<Role> getRoleListByPage(int count, int pageNo, String sortDirection, String... sortField) {
        Page<Role> rolesPage = rr.findAll(PageUtil.getPageable(count,pageNo,sortDirection,sortField));
        return rolesPage;
    }
}
